<?php

namespace app\admin\controller\prize;

use app\common\controller\Backend;
use app\common\model\PrizeDraw;
use Redis\QueueModel;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Queue;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Prize extends Backend
{
    
    /**
     * Prize模型对象
     * @var \app\admin\model\Prize
     */
    protected $model = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id,name,goods.name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Prize;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('goods')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('goods')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            foreach ($list as $k=>$v){
                $list[$k]['is_member'] = ($v['is_member']) ? '会员限定' : '非限定';
                $list[$k]['is_level'] = ($v['is_level']) ? '适用' : '不适用';
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     * TODO 如果已有用户参与抽奖，则禁止修改 某些字段
     *
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     * TODO 如果已有用户参与抽奖，则禁止删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 手动 或 每日执行定时任务 获取当日开奖列表
     * 加入队列
     * 更加开奖时间和当前时间 计算时间延时执行
     */
    public function openPrize()
    {
        //开奖任务
        $job = 'OpenPrize';
        //任务队列名
        $queue = 'openprize';

        //删除全部任务
        try {
            //$this->redis()->zRemRangeByRank('queues:' . $queue . ':delayed',0,-1);
            QueueModel::getInstance()->remQueueAll($queue);

        } catch (\RedisException $e){
            $msg = 'redis:' . $e->getMessage();
            $this->error($msg);
        }

        //读取抽奖列表 获取当日开奖要开奖的数据列表 (当前时间开始)
        $end = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $map = [
            'switch' => 1,
            'opentime' => ['BETWEEN',[time(),$end]],
        ];
        $prizeList = collection($this->model
            ->field('id,name,starttime,endtime,opentime,switch,total,num,is_level')
            ->where($map)
            //->whereTime('opentime','today')
            ->order('opentime asc')
            ->select())->toArray();

        //echo $this->model->getLastSql();exit;

        if (!$prizeList){
            $this->success('无可开奖记录！');
        }

        //设置延时开奖 成功 失败的记录
        $successList = $errorList = [];

        foreach ($prizeList as $k => $v){

            //未超过开奖时间的记录加入延时开奖
            if ($v['opentime'] > time()){
                //计算延时执行的时间
                $delay = $v['opentime'] - time();
                //延时加入队列
                $isPushed = Queue::later($delay,$job,$v,$queue);

                //判断是否是最后一个开奖发红包
                if ($k == (count($prizeList) - 1)){
                    $this->sendRedPacket($v);
                }

                //记录成功 失败的记录
                if( $isPushed !== false ){
                    $successList[] = $v;
                }else{
                    $errorList[] = $v;
                }

            }else{
                $errorList[] = $v;
            }
        }

        $total = count($successList);

        $data = compact('successList','errorList','total');


        $this->success('执行成功','',$data);

    }

    /**
     * 获取开奖任务队列
     * redis
     *
     * @throws \think\Exception
     */
    public function queueList()
    {
        $queue = 'openprize';

        if ($this->request->isAjax()) {

            try {
                //获取全部 openprize 计划任务
                //$queueList = $this->redis()->zRange('queues:' . $queue . ':delayed',0,-1,true);
                $queueList = QueueModel::getInstance()->getQueueAll($queue);

            } catch (\RedisException $e){
                $msg = 'redis:' . $e->getMessage();
                $this->error($msg);
            }

            $list = [];
            foreach ($queueList as $k => $v){
                $arr = json_decode($k,true);
                $arr['prize_id'] = $arr['data']['id'];
                $arr['data']['opentime'] = date('Y-m-d h:i:s',$arr['data']['opentime']);
                $arr['exec_time'] = date('Y-m-d h:i:s',$v);
                $list[] = $arr;

            }

            $list = $this->sortArrByManyField($list,'exec_time',SORT_ASC,'prize_id',SORT_ASC);

            $result = array("total" => count($list), "rows" => $list);

            return json($result);
        }

        return $this->view->fetch('queueList');
    }

    /**
     * 获取redis实例
     * @return \Redis
     */
    protected function redis()
    {
        if (!extension_loaded('redis')) {
            $this->error('redis扩展未安装');
        }
        //获取队列redis配置
        $options = Config::get('queue');
        $redis = new \Redis;
        try {
            $redis->connect($options['host'], $options['port'], $options['timeout']);
        }catch (\RedisException $e){
            //$msg = $e->getMessage();
            $this->error('redis服务未启动');
        }

        if ('' != $options['password']) {
            $redis->auth($this->options['password']);
        }

        if (0 != $options['select']) {
            $redis->select($options['select']);
        }

        return $redis;
    }

    protected function sortArrByManyField(){
        $args = func_get_args(); // 获取函数的参数的数组
        if(empty($args)){
            return null;
        }
        $arr = array_shift($args);
        if(!is_array($arr)){
            throw new Exception("第一个参数不为数组");
        }
        foreach($args as $key => $field){
            if(is_string($field)){
                $temp = array();
                foreach($arr as $index=> $val){
                    $temp[$index] = $val[$field];
                }
                $args[$key] = $temp;
            }
        }
        $args[] = &$arr;//引用值
        call_user_func_array('array_multisort',$args);
        return array_pop($args);
    }


    public function sendRedPacket($data)
    {
        $job = 'RedPacket';
        $queue = 'redpacket';

        try {
            //删除全部任务
            //$this->redis()->zRemRangeByRank('queues:' . $queue . ':delayed',0,-1);
            QueueModel::getInstance()->remQueueAll($queue);

        } catch (\RedisException $e){
            $msg = 'redis:' . $e->getMessage();
            $this->error($msg);
        }

        if (Config::get('site.noprize_redpacket')){
            //最后一次开奖 5分钟后发红包 防止未全部开奖
            $delay = $data['opentime'] + 300 - time();
            $expire_redpacket = Config::get('site.expire_redpacket');
            $param = [
                'send_time'     => $data['opentime'],
                'expire_redpacket'    => $expire_redpacket,
            ];
            //延时加入队列
            $isPushed = Queue::later($delay,$job,$param,$queue);
        }

        return true;
    }

    public function test()
    {
        // 获取当天 开始 结束 时间戳
        //$start = mktime(0,0,0,date('m'),date('d'),date('Y'));
        //$end = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;

        //获取 当天openprize计划任务
        //$queueList = $this->redis()->zRangeByScore('queues:test:delayed',$start,$end);

        //获取全部 openprize 计划任务
        //$queueList = $this->redis()->zRange('queues:test:delayed',0,-1);
        /*echo '<pre>';
        var_dump($queueList);exit;*/
        //$a = $this->redis()->zRemRangeByScore('queues:test:delayed','1602745775','1602745840');

        $t1 = '1602656400';
        $t2 = time();
        $delay = $t1 - $t2;
        $job = 'Job1';
        $data = [
            'key' => 'hello world',
        ];
        $queue = 'test';
        $isPushed = Queue::later(100,$job,$data['key'],$queue);
        //$isPushed = Queue::push( $job , $data,$queue );


        // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
        if( $isPushed !== false ){
            echo date('Y-m-d H:i:s') . " a new Hello Job is Pushed to the MQ"."<br>";
        }else{
            echo 'Oops, something went wrong.';
        }


        /*$queue = 'openpirze';
        $a = Queue::pop($queue);

        echo '<pre>';
        var_dump($a);exit;*/
    }
}
